package com.heima.search.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 陈辉
 * @data 2023 15:50
 */
@Component
public class ApUserTokenInterceptor implements HandlerInterceptor {

    @Override   //请求进入资源前拦截处理
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头，拿到用户id，存入ThreadLocal
        String userId = request.getHeader("userId");
        if (StringUtils.isNotEmpty(userId)){
            ApUserThreadLocalUtil.setUser(ApUser.builder().id(Integer.parseInt(userId)).build());
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WmThreadLocalUtil.clear();
    }
}
